/* 
    循环链表
*/
let { Node, LinkedList, defaultEquals } = require("./6_1");

class CircularLinkedList extends LinkedList {
  constructor(equalsFn = defaultEquals) {
    super(equalsFn);
  }
  // 重写insert
  insert(element, index) {
    if (index >= 0 && index <= this.count) {
      // 合法性需要经过判断
      let node = new Node(element);
      let current = this.head;
      if (index === 0) {
        // 队首
        if (this.head === null) {
          // 空链表
          this.head = node;
          node.next = this.head;
        } else {
          // 非空链表
          let current = this.head;
          node.next = current;
          this.head = node;
          current = this.getElementAt(this.size());
          current.next = node;
        }
      } else {
        // 其他位置
        let previous = this.getElementAt(index - 1); // 千万分清楚index / index - 1
        node.next = previous.next;
        previous.next = node;
      }
    }
  }

  // 移除任意位置元素
  removeAt(index) {
    if (index >= 0 && index < this.count) {
      // 合法性判断
      let current = this.head;
      if (index === 0) {
        // 队首
        if (this.count === 1) {
          // 只有一个元素
          this.head = undefined;
        } else {
          // 有多个元素
          const removed = this.head;
          current = this.getElementAt(this.size());
          this.head = this.head.next;
          currrent.next = this.head;
          current = removed;
        }
      } else {
        const previous = this.getElementAt(index - 1);
        current = previous.next;
        previous.next = current.next;
      }
      this.count--;
      return current.element;
    }
    return undefined;
  }
}
